package com.baidumap.administrator.happystudy.module.main;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioGroup;

import com.ab.http.OnMessageResponse;
import com.ab.util.AbToastUtil;
import com.ab.view.sliding.AbBottomTabView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.baidumap.administrator.happystudy.fragment.Fragment1;
import com.baidumap.administrator.happystudy.fragment.Fragment4;
import com.baidumap.administrator.happystudy.R;
import com.baidumap.administrator.happystudy.module.fenlei.fragment.FenLeiAllFragment;
import com.baidumap.administrator.happystudy.ui.Fragment_Four;
import com.baidumap.administrator.happystudy.base.AppBaseActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList; 
import java.util.List;

import butterknife.Bind;

/**
 * 描述：
 * 作者：xiaoxing on 17/4/21 10:04
 * 邮箱：2235445233@qq.com
 */
public class MainActivity extends AppBaseActivity implements OnMessageResponse, LocationSource, AMapLocationListener {

    @Bind(R.id.mBottomTabView)
    AbBottomTabView mBottomTabView;
    private static List<Drawable> tabDrawables = null;

    private AMap aMap;
    private MapView mapView;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private RadioGroup mGPSModeGroup;

    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);
    private Double mLatitude, mLongitude;//维度、精度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_main_tab;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        initBottomTab();

        mapView = new MapView(this);
        mapView.onCreate(mSavedInstanceState);// 此方法必须重写
        init();
    }

    @Override
    public void doBusiness(Context mContext) {
        super.doBusiness(mContext);

        getBundleValue();
        setTitleHidden();

    }

    /**
     * initBottomTab
     */
    public void initBottomTab() {
        //如果里面的页面列表不能下载原因：
        //Fragment里面用的AbTaskQueue,由于有多个tab，顺序下载有延迟，还没下载好就被缓存了。改成用AbTaskPool，就ok了。
        //或者setOffscreenPageLimit(0)

        //缓存数量
        mBottomTabView.getViewPager().setOffscreenPageLimit(5);

        //禁止滑动
        /*mBottomTabView.getViewPager().setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}

		});*/

        //mBottomTabView.setOnPageChangeListener(listener);

        Fragment1 page1 = new Fragment1();
        FenLeiAllFragment page2 = new FenLeiAllFragment();
//        Fragment_Three page3 = new Fragment_Three();
        Fragment_Four page4 = new Fragment_Four();
        Fragment4 page5 = new Fragment4();

        List<Fragment> mFragments = new ArrayList<Fragment>();
        mFragments.add(page1);
        mFragments.add(page2);
//        mFragments.add(page3);
        mFragments.add(page4);
        mFragments.add(page5);

        List<String> tabTexts = new ArrayList<String>();
        tabTexts.add(getString(R.string.one));
        tabTexts.add(getString(R.string.two));
//        tabTexts.add(getString(R.string.three));
        tabTexts.add(getString(R.string.four));
        tabTexts.add(getString(R.string.five));

        //设置样式
        mBottomTabView.setTabTextColor(Color.BLACK);
        mBottomTabView.setTabTextSize(25);
        mBottomTabView.setTabSelectColor(AbBottomTabView.tabSelectColor);
        mBottomTabView.setTabSlidingColor(0);
//        mBottomTabView.setTabBackgroundResource(R.drawable.tab_bg2);
        mBottomTabView.setTabLayoutBackgroundResource(R.drawable.tab_bg);

        //注意图片的顺序
        tabDrawables = new ArrayList<Drawable>();
        tabDrawables.add(getResources().getDrawable(R.mipmap.index1_nor));
        tabDrawables.add(getResources().getDrawable(R.mipmap.index1_pre));
        tabDrawables.add(getResources().getDrawable(R.mipmap.index2_nor));
        tabDrawables.add(getResources().getDrawable(R.mipmap.index2_pre));
        tabDrawables.add(getResources().getDrawable(R.mipmap.index3_nor));
        tabDrawables.add(getResources().getDrawable(R.mipmap.index3_pre));
        tabDrawables.add(getResources().getDrawable(R.mipmap.index4_nor));
        tabDrawables.add(getResources().getDrawable(R.mipmap.index4_pre));
//        tabDrawables.add(getResources().getDrawable(R.mipmap.five_normal));
//        tabDrawables.add(getResources().getDrawable(R.mipmap.five_pressed));
        mBottomTabView.setTabCompoundDrawablesBounds(0, 0, 40, 40);
        //演示增加一组
        mBottomTabView.addItemViews(tabTexts, mFragments, tabDrawables);

        mBottomTabView.setTabPadding(10, 10, 10, 10);
        mBottomTabView.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                switch (position) {
                    case 3:

                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 初始化
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }

    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        setupLocationStyle();
    }

    private void setupLocationStyle() {
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.mipmap.gps_point));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(STROKE_COLOR);
        //自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(5);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(FILL_COLOR);
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                mLatitude = amapLocation.getLatitude();
                mLongitude = amapLocation.getLongitude();

//                ToastUtil.showMessage(this, amapLocation.getCity());
                FenLeiAllFragment.toolbar_title.setText(amapLocation.getCity());

            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
//                mLocationErrText.setVisibility(View.VISIBLE);
//                mLocationErrText.setText(errText);
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    /**
     * 初始化头部右侧
     */
    public static void initTitleRightLayout() {
//        mAbTitleBar.clearRightView();
//        View rightViewMore = mInflater.inflate(R.layout.geren_shuaxin, null);
//        mAbTitleBar.addRightView(rightViewMore);

//        Button about = (Button) rightViewMore.findViewById(R.id.moreBtn);
//
//        about.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                startActivity(Activity_Main.this, Loginclass);
//            }
//
//        });
    }

    private void getBundleValue() {
        String tabSelected = "";
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            tabSelected = bundle.getString("tabSelected");
            if (tabSelected.equals("cart")) {
                mBottomTabView.getViewPager().setCurrentItem(3);
            }
            if (tabSelected.equals("shouye")) {
                mBottomTabView.getViewPager().setCurrentItem(0);
            }
        }
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Object mHelperUtils;
                AbToastUtil.showToast(this, "再按一次退出程序");
                mExitTime = System.currentTimeMillis();

            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onMessageResponse(String url, JSONObject jo) throws JSONException {

    }

    @Override
    public void onMessageResponse(String url, JSONArray jo) throws JSONException {

    }

    @Override
    public void onMessageResponse(String url, String str) throws Exception {

    }

}